/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package contest.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author Admin
 */
public class ErrorLog {

    public static void catchException(String path, Exception ex) {
        if (path != null && FileUtil.isExists(path)) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Date date = new Date();
            String error = dateFormat.format(date);
            if (ex != null && ex.getStackTrace() != null && ex.getStackTrace().length > 0) {
                error += " : " + (ex.getStackTrace()[0].getFileName()
                        + " : " + ex.getStackTrace()[0].getClassName()
                        + " : " + ex.getStackTrace()[0].getMethodName()
                        + " : " + ex.getStackTrace()[0].getLineNumber())
                        + " : " + ex.getMessage();
            } else {
                error += " : " + PropertiesBundle.EXCEPTION.getString("util.errorlog.text_1");
            }
            BufferedWriter writer = null;
            try {
                error = error + "\n";
                File file = new File(path);
                String content = FileUtil.getContentFile(path);
                writer = new BufferedWriter(new FileWriter(file));
                writer.write(content + error);
                System.out.println(error);
            } catch (Exception ex2) {
                ex2.printStackTrace(System.out);
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException ex1) {
                        ErrorLog.catchException(ex1);
                    }
                }
            }
        }
    }

    public static void catchException(Exception ex) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        String error = dateFormat.format(date);
        if (ex != null && ex.getStackTrace() != null && ex.getStackTrace().length > 0) {
            error += " : " + (ex.getStackTrace()[0].getFileName()
                    + " : " + ex.getStackTrace()[0].getClassName()
                    + " : " + ex.getStackTrace()[0].getMethodName()
                    + " : " + ex.getStackTrace()[0].getLineNumber())
                    + " : " + ex.getMessage();
        } else {
            error += " : " + PropertiesBundle.EXCEPTION.getString("util.errorlog.text_1");
        }
        System.out.println(error);
    }
}
